//从云数据库获取数据
const getCloudDbData = (key) => {
  const db = wx.cloud.database();
  return db.collection('XyKey').doc(key).get().then(res => {
    return res.data;
  }, err => {
    return ""
  });
}
//把数据存储到云数据库
const setCloudDbData = (key, data) => {
  const db = wx.cloud.database();
  return db.collection('XyKey').doc(key).set({
    data: data
  });
}
//删除云数据
const removeCloudDbData = (key) => {
  const db = wx.cloud.database();
  return db.collection('XyKey').doc(key).remove();
}

//从存储文件获取数据
const getStorageData = (key) => {
  return wx.getStorageSync(key);
};
//把数据存储到文件
const setStorageData = (key, data) => {
  wx.setStorageSync(key, data);
};

//深层拷贝
const copyObject = (obj) => {
  return JSON.parse(JSON.stringify(obj));
}
//查找并返回第一个
const firstOrDefault = (arry, fun) => {
  for (let i = 0; i < arry.length; i++) {
    if (fun(arry[i])) {
      return arry[i];
    }
  }
  return undefined;
}

//返回
const navigateBack = (delta = 1) => {
  wx.navigateBack({
    delta: delta
  })
}
//页面跳转 jsonParam
const navigateTo = (url, parameter) => {
  if (!parameter) {
    wx.navigateTo({
      url: url
    });
    return;
  }

  //分隔符
  const segmenter = url.indexOf('?') == -1 ? '?' : '&';
  wx.navigateTo({
    url: url + segmenter + 'jsonParam=' + encodeURIComponent(JSON.stringify(parameter)),
  });
}
//解析 jsonParam
const jsonParamParse = (jsonParam) => {
  return JSON.parse(decodeURIComponent(jsonParam))
}
/*信息提示 */
const showToast = (title = "提示", icon = "none", duration = 1500) => {
  wx.showToast({
    title: title,
    icon: icon,
    duration: duration,
    mask: true
  });
}

//复制到剪切板，2分钟后自动清除剪切板（好像不成功！）
const setClipboardData = (content) => {
  wx.setClipboardData({
    data: content,
    success(res) { //可以考虑设置一个定时器，2分钟后清除剪切板
    }
  })
}

const checkIsSupportSoterAuthentication = (option) => {
  const notSupported = () => {
    wx.showModal({
      title: '错误!',
      content: '您的设备不支持指纹识别',
      showCancel: false
    })
  }
  wx.checkIsSupportSoterAuthentication({
    success: (res) => {
      if (!res || res.supportMode.length === 0 || res.supportMode.indexOf('fingerPrint') < 0) {
        notSupported();
        option.supportFail(res);
        return;
      }
      const checkOption = {
        isStartAuth: option.isStartAuth,
        success: (res) => {
          option.success(res);
        },
        authentFail: (err) => {
          option.authentFail(err);
        },
        enrolledFail: (err) => {
          option.enrolledFail(err);
        }
      };
      checkIsSoterEnrolledInDevice(checkOption);
    },
    fail: (err) => {
      console.error(err);
      notSupported();
      //设备不支持指纹错误
      option.supportFail(err);
    }
  })
};
//检测设备是否录入指纹
const checkIsSoterEnrolledInDevice = (option) => {
  wx.checkIsSoterEnrolledInDevice({
    checkAuthMode: 'fingerPrint',
    success: (res) => {
      if (parseInt(res.isEnrolled, 10) <= 0) {
        wx.showModal({
          title: '错误!',
          content: '您暂未录入指纹信息，请录入后重试',
          showCancel: false
        })
        return
      }
      if (option.isStartAuth != undefined && option.isStartAuth == false) {
        option.success(res);
        return;
      }
      //如果开始验证指纹
      startSoterAuthentication({
        success: (res) => {
          option.success(res);
        },
        authentFail: (err) => {
          option.authentFail(err);
        }
      })
    },
    fail: (err) => {
      //没有录入指纹错误
      option.enrolledFail(err);
    }
  });
};
//开始验证指纹
const startSoterAuthentication = (option) => {
  let challenge = option.challenge;
  if (option.challenge == undefined || option.challenge == '') {
    challenge = 'XyKey' + Math.ceil(Math.random() * 10);
  }

  wx.startSoterAuthentication({
    requestAuthModes: ['fingerPrint'],
    challenge: challenge, //挑战因子,
    authContent: 'XyKey认证指纹',
    success: (res) => {
      option.success(res);
    },
    fail: (err) => {
      //认证失败错误
      option.authentFail(err);
    }
  })
};

module.exports = {
  getCloudDbData: getCloudDbData,
  setCloudDbData: setCloudDbData,
  removeCloudDbData: removeCloudDbData,

  getStorageData: getStorageData,
  setStorageData: setStorageData,

  copyObject: copyObject,
  firstOrDefault: firstOrDefault,

  navigateBack: navigateBack,
  navigateTo: navigateTo,
  jsonParamParse: jsonParamParse,
  showToast: showToast,
  setClipboardData: setClipboardData,

  checkIsSupportSoterAuthentication: checkIsSupportSoterAuthentication,
  checkIsSoterEnrolledInDevice: checkIsSoterEnrolledInDevice,
  startSoterAuthentication: startSoterAuthentication
}